package com.mt.api.core.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.mt.common.enums.AppReturnCodeEnum;
import com.mt.api.constants.constant.JwtConstants;
import com.mt.api.constants.threadlocal.JwtUserThreadLocal;
import com.mt.api.constants.threadlocal.TokenThreadLocal;
import com.mt.api.modules.domain.dto.AppBossDto;
import com.mt.api.modules.domain.dto.JwtUserDto;
import com.mt.api.util.JwtUserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Objects;

/**
 * @Author: plover
 * @Date: 2020/07/08/11:24 上午
 * @Description:
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Order(2)
public class TokenHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            String token = request.getHeader(JwtConstants.AUTH_HEADER);
            if (StringUtils.isNotEmpty(token)) {
                //账号互踢逻辑
                boolean verify = JwtUserUtils.verifyAccountToken(token);
                if (!verify) {
                    writerMsg(response, AppReturnCodeEnum.UN_LOGIN);
                    return false;
                }

                JwtUserDto jwtUserDto = JwtUserUtils.getJwtUserByToken(token);
                //token获取用户数据为空，则说明token失效，需要重新登录
                if (Objects.isNull(jwtUserDto)) {
                    writerMsg(response, AppReturnCodeEnum.UN_LOGIN);
                    return false;
                }
                AppBossDto appBoss = jwtUserDto.getAppBoss();
                if (Objects.isNull(appBoss)) {
                    writerMsg(response, AppReturnCodeEnum.UN_LOGIN);
                    return false;
                }
                TokenThreadLocal.add(token);
                JwtUserThreadLocal.add(jwtUserDto);
                return true;
            } else {
                writerMsg(response, AppReturnCodeEnum.UN_LOGIN);
                return false;
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TokenThreadLocal.remove();
        JwtUserThreadLocal.remove();
    }

    /**
     * 返回信息
     *
     * @param response
     */
    private void writerMsg(HttpServletResponse response, AppReturnCodeEnum anEnum) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            JSONObject messageObj = new JSONObject();
            messageObj.put("code", anEnum.getCode());
            messageObj.put("message", anEnum.getMsg());
            response.getWriter().print(messageObj.toString());
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) {
        T annotation = handler.getBeanType().getAnnotation(annotationType);
        if (annotation != null) return annotation;
        return handler.getMethodAnnotation(annotationType);
    }

}
